Hook과 State

✒️ 2025-05-28 10:40 내용 수정


Hook

함수 Component에서 React state와 생명주기 기능을 연동(Hook into)할 수 있게 해주는 함수


State

React에서 사용하는 component에 특화된 메모리


useState(State Hook)

state를 함수 Component 내에서 사용할 수 있게 해주는 Hook

import { useState } from 'react';

const [ value, setValue ] = useState(0);
import {useState} from 'react';

function Test() {
	const[count, setCount] = useState(0);
	const[name, setName] = useState('Tom');
	const[fruits, setFruits] = useState(['banana', 'apple', 'grape', 'berry']);

	return(
		<>
			<button onClick={()=>setCount(count + 1)}>Click Me</button>
			<button onClick={()=>setName('Jerry')}>Name?</button>
			<button onClick={()=>setFruits(['apple', 'kiwi'])}>Fruits</button>
		</>
	)
}
function Counter() {
    const [count, setCount] = useState(0);
    const increase = () => {
        // count에 1을 더한 새로운 값을 할당
        // count++는 상수 자체에 연산 수행
        setCount(count + 1);
    }
    const decrease = () => {
        setCount(count - 1);
    }
}
export {Counter, NameList};